package com.user.servlet;

import com.user.entity.BookInfo;
import com.user.entity.Page;
import com.user.entity.Users;
import com.user.service.IUserService;
import com.user.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "UserBorrowBookListServlet", value = "/UserBorrowBookListServlet")
public class UserBorrowBookListServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String username = request.getParameter("username");
        IUserService userService = new UserServiceImpl();


        int totalCount = userService.getBorrowBooksCount(username);//数据总数

        //将分页所需的5个字段（其中有1个自动计算，因此实际只需要组装4个即可），组装到page对象之中
        Page page = new Page();

        String cPage = request.getParameter("currentPage");

        if (cPage == null) {
            cPage = "1";
        }

        int currentPage = Integer.parseInt(cPage);
        page.setCurrentPage(currentPage);
//		int currentPage = 2;//页码


        //注意 顺序
        //总数据数
        page.setTotalCount(totalCount);

		/* currentPage：当前页（页码）
	  	 students :当前页的数据集合（当前页的所有学生）

		*/

        int pageSize = 5;
        page.setPageSize(pageSize);


        List<BookInfo> bookList = userService.
                queryUserBorrowBooks(new Users(username, "0"));

        //获得总页数
        int totalPage = page.getTotalPage();
        if (totalPage <= currentPage) {
            page.setCurrentPage(totalPage);
        }


        //包含学生数据
        page.setBookList(bookList);

        request.setAttribute("p", page);
        String adminname = request.getParameter("adminname");

        if (adminname != null) {
            request.setAttribute("username", username);

            request.getRequestDispatcher("Admin/borrowBooksList.jsp").forward(request, response);
        } else
            request.getRequestDispatcher("User/borrowBooksList.jsp").forward(request, response);

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
